﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using COMOSOFT.Class;
using COMOSOFT.MatarialManagement.Forms;
using System.Data.SqlClient;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraEditors;
using MSoft.Shipping.Control;
using DevExpress.XtraGrid.Views;
using System.Data.SqlTypes;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraGrid.Views.Base;
using System.Data.Odbc;
using Excel = Microsoft.Office.Interop.Excel;
using System.Xml;
using System.IO;
using DevExpress.XtraPrinting;
using DevExpress.XtraBars;


namespace COMOSOFT.MatarialManagement.Forms
{
    public partial class FrmStyleDetails : Form
    {       
        int MALID;
        DataTable dtbMA;
        string txt,value;
        ClassShare cls = new ClassShare("FrmStyleDetails");        
        string Cus = null;
        string StyleNo = null,OIDs=null;
        List<string> ListItems = new List<string>();

        int MAID, MADID, OID;        
        string Items;
        int flag;        

        public FrmStyleDetails(int MALID) 
        {
            InitializeComponent();
            this.MALID = MALID;
            if (MALID == -1)
            {
                mAListMasterTableAdapter.Fill(dataSetMatarial.MAListMaster, MALID);
            }                  
        }

        #region[Refresh Data]
        private void RefreshMALDetails()
        {
            this.sp_MAListDetailViewTableAdapter.Fill(dataSetMatarial.sp_MAListDetailView, MALID);
        }
        #endregion

        #region[AddNew]

        public void AddNew()
        {
            mAListMasterBindingSource.AddNew();
            sp_CustomerListTableAdapter.Fill(dataSetOrderManagement.sp_CustomerList, ClassShare.Usid);
            panel_Material.Enabled = false;
            txt_issuedate.Text = DateTime.Now.ToShortDateString();
            lookUp_EID.EditValue = Convert.ToInt64(ClassShare.Usid);
        }
        #endregion

        #region [Show CusPO]
        private void ShowCusPO()
        {
            try
            {
                    spCusPOBindingSource.EndEdit();
                    dataSetMatarial.sp_CusPO.AcceptChanges();
                    DataRow[] dtr = dataSetMatarial.sp_CusPO.Select("IsChecked=True");
                    txt = null;
                    value = null;
                    if (dtr.Count()>0)
                    {
                        //int[] item = view.GetSelectedRows();
                        for (int i = 0; i < dtr.Count();i++ )
                        {
                            txt += dtr[i]["PO"].ToString() + ", ";
                            value += dtr[i]["OID"].ToString() + ", ";
                        }
                    }
                    if (txt != null)
                    {
                        txt = txt.Substring(0, txt.Length - 2);
                        value = value.Substring(0, value.Length - 2);
                    }
                    gridLookUp_POs.EditValue = value;
                    txt_PO.Text = txt;
            }
            catch
            {
               // MessageBox.Show("Disconnect database! Please try again!", "Disconnect...", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region [LoadData]
        public void LoadData()
        {
            try
            {
                //sp_SelectAMListDetailsTableAdapter.Fill(dataSetMatarial.sp_SelectAMListDetails);
                sp_CustomerListTableAdapter.Fill(dataSetOrderManagement.sp_CustomerList, ClassShare.Usid);                
                if (MALID > 0)
                {
                    mAListMasterTableAdapter.Fill(dataSetMatarial.MAListMaster, MALID);
                    DataTable dtb = dataSetMatarial.MAListMaster;
                    Cus = dtb.Rows[0]["Customer"].ToString();
                    StyleNo = dtb.Rows[0]["StyleNo"].ToString();
                    sp_MAListDetailViewTableAdapter.Fill(dataSetMatarial.sp_MAListDetailView, MALID);
                    sp_CusPOTableAdapter.Fill(dataSetMatarial.sp_CusPO,MALID, Cus, StyleNo);
                    ShowCusPO();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Update MAMaster]
        public void UpdateData()
        {
            try
            {
                if (MALID == -1)
                {
                    mAListMasterBindingSource.EndEdit();
                    mAListMasterTableAdapter.Update(dataSetMatarial.MAListMaster);
                    dataSetMatarial.MAListMaster.AcceptChanges();
                    this.Text = txt_MalNo.Text;                    
                    if (panel_Material.Enabled == false)
                    {
                        panel_Material.Enabled = true;
                        MALID = Convert.ToInt32(txt_malid.Text);
                    }
                }
                else
                {
                    mAListMasterBindingSource.EndEdit();
                    mAListMasterTableAdapter.Update(dataSetMatarial.MAListMaster);
                    dataSetMatarial.MAListMaster.AcceptChanges();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Load MaterialDetails]
        private void FrmStyleDetails_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'dataSetMatarial.Supplier' table. You can move, or remove it, as needed.
            this.supplierTableAdapter.Fill(this.dataSetMatarial.Supplier);
            this.employeeTableAdapter.Fill(this.dataSetOrderManagement.Employee);            
            this.orderDetailsTableAdapter.Fill(this.dataSetOrderManagement.OrderDetails);
            this.sp_SelectAMListDetailsTableAdapter.Fill(this.dataSetMatarial.sp_SelectAMListDetails);            
            new BandedCellSelectionHelper(gridControl_Material);
            
            ListItems.Add(txt_MalNo.Text);
            ListItems.Add(txt_customer.Text);
            ListItems.Add(gridLookUpEdit_styleno.Text);
            ListItems.Add(gridLookUp_POs.Text);
            ListItems.Add(txt_PO.Text);
            ListItems.Add(txt_issuedate.EditValue.ToString());

            AcceptButton = bnt_OKCons;
        }
        #endregion       

        #region [Choose MA Details]
        private void repositorySelectMADetails_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            try
            {                
                var glk = bandedGridView_Material.ActiveEditor as GridLookUpEdit;
                var view = glk.Properties.View as GridView;
                if (view.FocusedRowHandle >= 0)
                {
                    try
                    {
                        int MAID = Convert.ToInt32(view.GetFocusedRowCellValue("MAID"));
                        int No = Convert.ToInt32(bandedGridView_Material.GetRowCellValue(bandedGridView_Material.RowCount - 2, "No")) + 1;
                        OIDs = value;
                        PopUpMA PUMA = new PopUpMA(MALID, MAID,OIDs,No);
                        PUMA.ShowDialog();
                        LoadData();
                        LoadDataMA();                       
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        view.FocusedColumn = view.Columns[0];
                    }
                }
            }
            catch
            { 
            }
        }
        #endregion

        #region [Refresh - Delete MADetails]
        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshMALDetails();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Delete row selected?", "Deletion....?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    int MALDID = Convert.ToInt32(bandedGridView_Material.GetFocusedDataRow()["MALDID"]);
                    if (MALDID != 0)
                    {
                        cls.UpdateData("sp_MAListDetailDelete", new string[1] { "@MALDID" }, new object[1] { MALDID });
                        RefreshMALDetails();
                    }
                }
            }
            catch
            {
                MessageBox.Show("No item for delete!","Can't not Delete!",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region [Delete MALMaster]
        public void DeleteMaster()
        {
            try
            {
                if (MessageBox.Show("Are you sure you want to delete?", "Delete item", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    this.dataSetMatarial.MAListMaster.Rows[0].Delete();
                    mAListMasterTableAdapter.Update(dataSetMatarial.MAListMaster);
                    dataSetMatarial.MAListMaster.AcceptChanges();
                    this.Close();
                }
            }
            catch
            {
                MessageBox.Show("You can't delete this item, Please check objects relation!", "Error Delete",MessageBoxButtons.OK, MessageBoxIcon.Error);
                mAListMasterTableAdapter.Fill(dataSetMatarial.MAListMaster, MALID);                
            }
        }
        #endregion

        #region [Load CusStyleNo]
        private void txt_customer_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                sp_CusStyleNoTableAdapter.Fill(dataSetMatarial.sp_CusStyleNo, txt_customer.EditValue.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [MAStyleNo]
        private void gridLookUpEdit_styleno_EditValueChanged(object sender, EventArgs e)
        {
            if (txt_customer.EditValue != null)
            {
                 Cus = txt_customer.EditValue.ToString();
                 StyleNo = gridLookUpEdit_styleno.EditValue.ToString();
                if (Cus != null && StyleNo != null)
                {
                    sp_CusPOTableAdapter.Fill(dataSetMatarial.sp_CusPO,MALID, Cus, StyleNo);
                }
                txt_MalNo.Text = gridLookUpEdit_styleno.EditValue + " - " + txt_PO.EditValue;
            }
        }

        private void txt_PO_EditValueChanged(object sender, EventArgs e)
        {
            txt_MalNo.Text = gridLookUpEdit_styleno.EditValue + " - " + txt_PO.EditValue;
        }
        #endregion     

        #region [Init BackgroundWorker]
        public void RunBackroundWorker()
        {
            backgroundWorker_MADetails.RunWorkerAsync();
        }
       #endregion

        #region[LoadDataMaListDetails]
        private void LoadDataMA()
        {
            try
            {
                int numcol = 14;
                dtbMA = cls.GetData("sp_MAListDetailView", new string[1] { "@malid" }, new object[1] { MALID });
                gridControl_Material.DataSource = dtbMA;
                Int16 TotalQty = 0;
                BandedGridView view = gridControl_Material.MainView as BandedGridView;
                gridBand_Color.Columns.Clear();
                gridBand_Quantity.Columns.Clear();                
                //Popup Color
                RepositoryItemPopupContainerEdit popup;                
                popup = new DevExpress.XtraEditors.Repository.RepositoryItemPopupContainerEdit();
                popup.AutoHeight = false;
                popup.Name = "repositoryItemPopupContainerEdit_color";
                popup.PopupControl = popup_Color;               

                for (int i = numcol; i < dtbMA.Columns.Count; i++)
                {
                    if (dtbMA.Columns[i].ColumnName.Substring(0, 5) == "Color")
                    {                        
                        BandedGridColumn colColor = view.Columns.AddVisible(dtbMA.Columns[i].ColumnName) as BandedGridColumn;                       
                        string[] Color = dtbMA.Columns[i].ColumnName.Substring(5).Split(new string[] { ":" }, 2, 0);
                        colColor.Caption ="Color\n"+Color[0];                       
                        //Popup Color                       
                        colColor.ColumnEdit = popup;                       
                        //------------------------------
                        colColor.Width = 100;                        
                        this.gridBand_Color.Columns.Add(colColor);
                    }
                    if (dtbMA.Columns[i].ColumnName.Substring(0, 8) == "Quantity")
                    {
                        BandedGridColumn colQuantity = view.Columns.AddVisible(dtbMA.Columns[i].ColumnName) as BandedGridColumn;
                        colQuantity.Caption = dtbMA.Columns[i].ColumnName;
                        colQuantity.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                        colQuantity.DisplayFormat.FormatString = "{0:n0}";
                        colQuantity.SummaryItem.FieldName = dtbMA.Columns[i].ColumnName;
                        colQuantity.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                        colQuantity.SummaryItem.DisplayFormat = "Total: {0:n0}";
                        colQuantity.OptionsColumn.ReadOnly = true;
                        colQuantity.Width = 100;
                        colQuantity.OptionsColumn.AllowEdit = false;
                        this.gridBand_Quantity.Columns.Add(colQuantity);
                    }                   
                }
                dtbMA.Columns.Add("colTotalQty", typeof(int));
                for (int row = 0; row < dtbMA.Rows.Count; row++)
                {
                    TotalQty = 0;
                    for (int col = numcol; col < dtbMA.Columns.Count; col++)
                    {
                        if (dtbMA.Columns[col].ColumnName.Substring(0, 8) == "Quantity" && dtbMA.Rows[row][col].ToString() != "")
                        {
                            TotalQty += Convert.ToInt16(dtbMA.Rows[row][col]);
                        }
                    }
                    dtbMA.Rows[row]["colTotalQty"] = TotalQty;
                }

                BandedGridColumn colTotal = view.Columns.AddVisible(dtbMA.Columns["colTotalQty"].ColumnName) as BandedGridColumn;
                colTotal.Caption = "Total \n Quantity";
                colTotal.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                colTotal.DisplayFormat.FormatString = "{0:n0}";
                colTotal.SummaryItem.FieldName = dtbMA.Columns["colTotalQty"].ColumnName;
                colTotal.SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                colTotal.SummaryItem.DisplayFormat = "Total: {0:n0}";
                colTotal.Width = 100;
                colTotal.OptionsColumn.ReadOnly = true;
                colTotal.OptionsColumn.AllowEdit = false;
                colTotal.AppearanceCell.ForeColor=System.Drawing.Color.Blue;                
                this.gridBand_Quantity.Columns.Add(colTotal);


                //view.BestFitColumns();
                view.ColumnPanelRowHeight = 50;
                System.Threading.Thread.Sleep(10);
                new BandedCellSelectionHelper(bandedGridView_Material);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void backgroundWorker_MADetails_DoWork(object sender, DoWorkEventArgs e)
        {
           // LoadDataMA();            
        }

        #region [Load MA Details]
        private void backgroundWorker_MADetails_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            LoadDataMA();
        }
        #endregion

        #region [Get OIs]
        private void gridLookUp_POs_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            ShowCusPO();
        }

        private void gridLookUp_POs_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            e.DisplayText = txt;
        }
        #endregion

        #region [Set Type]
        private void bandedGridView_Material_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            BandedGridView view = sender as BandedGridView;            
            //view.SetRowCellValue(e.RowHandle,"Type", "Production");
            view.SetRowCellValue(e.RowHandle, "No",Convert.ToInt32(view.GetRowCellValue(view.RowCount-2,"No"))+1);
        }
        #endregion

        #region [RowCellClick]
        private void gridLookUp_ListPO_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            try
            {
                if (Convert.ToBoolean(e.CellValue) == true)
                {
                    gridLookUp_ListPO.SetRowCellValue(e.RowHandle, "IsChecked", false);
                }
                else
                {
                    if (Convert.ToBoolean(e.CellValue) == false)
                       gridLookUp_ListPO.SetRowCellValue(e.RowHandle, "IsChecked", true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[Update MADetais]
        private void bandedGridView_Material_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                string MALDID, Type, Remark, Using;
                object No, Cons;
                if (bandedGridView_Material.IsNewItemRow(e.RowHandle)==false)
                {
                    MALDID = bandedGridView_Material.GetDataRow(e.RowHandle)["MALDID"].ToString();
                    No = bandedGridView_Material.GetDataRow(e.RowHandle)["No"];
                    Cons = bandedGridView_Material.GetDataRow(e.RowHandle)["Cons"];
                    Type = bandedGridView_Material.GetDataRow(e.RowHandle)["Type"].ToString();
                    Remark = bandedGridView_Material.GetDataRow(e.RowHandle)["Remarks"].ToString();
                    Using = bandedGridView_Material.GetDataRow(e.RowHandle)["Using"].ToString();

                    cls.UpdateData("sp_MAListDetailUpdate", new string[] { "@MALDID", "@No", "@Cons", "@Remark", "@Type", "@Using" }, new object[] { MALDID, No, Cons, Remark, Type, Using });
                    LoadDataMA();
                }
                
            }
            catch
            {               
            }
        }
        #endregion
        //Color
        #region[Choose Color]
        private void bnt_Choosecolor_Click(object sender, EventArgs e)
        {
            try
            {
                if (gridView_Color.FocusedRowHandle >= 0)
                {                    
                    MADID=Convert.ToInt32(gridView_Color.GetFocusedDataRow()["MADID"]);
                    if(flag==1)
                      cls.UpdateData("sp_MAUpadteColor", new string[] { "@OID", "@Items", "@MADID"}, new object[] { OID, Items, MADID});
                    else
                    {
                        DataTable ID = cls.GetData("sp_MAInsertColor", new string[] { "@OID", "@Items", "@MADID" }, new object[] { OID, Items, MADID });
                        DataTable dtb = cls.GetData("sp_MAGetSizeUsing", new string[] { "@Items" }, new object[] { Items});
                        for (int i = 0; i < dtb.Rows.Count; i++)
                        {
                            cls.UpdateData("sp_MAUpdateSizeUsing", new string[] {"@SBID","@MALDID","@Qty","Remark" }, new object[] {Convert.ToInt32(dtb.Rows[i]["SBID"]),ID.Rows[0]["ID"],Convert.ToInt16(dtb.Rows[i]["Qty"]),dtb.Rows[i]["Remarks"].ToString()});
                        }
                    }
                    LoadDataMA();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[Show Popup]
        private void bandedGridView_Material_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            try
            {                
                BandedGridView view = sender as BandedGridView;               
                if (e.Column.FieldName == "Art")
                {
                    sp_SelectAMListDetailsTableAdapter.Fill(dataSetMatarial.sp_SelectAMListDetails);
                }
                if (view.IsNewItemRow(view.FocusedRowHandle))
                {
                    view.SetFocusedRowCellValue("Type", "Production");
                }
                if (view.IsNewItemRow(e.RowHandle) == false)
                {
                    if (e.RowHandle >= 0)
                    {
                        string name = e.Column.Caption + "default";
                        if (name.Substring(0, 5) == "Color")
                        {
                            sp_ChooseColorTableAdapter.Fill(dataSetMatarial.sp_ChooseColor, MAID);
                            if (e.CellValue.ToString() != "")
                                flag = 1;
                            else
                                flag = 0;
                            DataRow rows = view.GetFocusedDataRow();
                            MAID = Convert.ToInt32(rows["MAID"]);
                            string[] val = e.Column.Name.Split(new string[] { ":" }, 2, 0);
                            Items = rows["MALDID"].ToString();
                            OID = Convert.ToInt32(val[1]);
                        }
                        if (e.Column.FieldName == "Size")
                        {
                            DataRow rows = view.GetFocusedDataRow();
                            Items = rows["MALDID"].ToString();
                            sp_MAChooseSizeTableAdapter.Fill(dataSetMatarial.sp_MAChooseSize, Items);
                        }
                        if (e.Column.FieldName == "Cons")
                        {
                            DataRow rows = view.GetFocusedDataRow();
                            Items = rows["MALDID"].ToString();
                            sp_MAConsTableAdapter.Fill(dataSetMatarial.sp_MACons, Items);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
        //Size
        #region[Check Size]
        private void gridView_Size_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            try
            {
                if (Convert.ToBoolean(e.CellValue)==true)
                {
                    gridView_Size.SetRowCellValue(e.RowHandle, "IsChecked", false);
                }
                else
                {
                    if (Convert.ToBoolean(e.CellValue) == false)
                        gridView_Size.SetRowCellValue(e.RowHandle, "IsChecked", true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion 

        #region[Update Size]
        int Qty;
        private void bnt_OK_Click(object sender, EventArgs e)
        {
            try
            {
                Qty = 0;            
                cls.UpdateData("sp_MADeleteSize", new string[] { "@Items" }, new object[] { Items });
                DataRow[] rows = dataSetMatarial.sp_MAChooseSize.Select("IsChecked=True");
                string[] MALDIDs = Items.Split(new string[] { "," }, 0);
                
                if (rows.Count() > 0)
                {
                    foreach (DataRow item in rows)
                    {                      
                        foreach (string id in MALDIDs)
                        {
                            DataTable dtb = cls.GetData("sp_MAGetSize", new string[] { "@MALDID", "@Items" }, new object[] {Convert.ToInt32(id),item["SBID"].ToString() });
                            if (dtb.Rows.Count > 0)
                            {  
                                cls.UpdateData("sp_MAUpdateSize", new string[] { "@MALDID", "@SBID", "@Qty" }, new object[] { Convert.ToInt32(id), Convert.ToInt32(dtb.Rows[0]["SBID"]), Convert.ToInt16(dtb.Rows[0]["Qty"]) });
                            }
                        }
                        Qty += Convert.ToInt16(item["Qty"]);
                    }
                    cls.UpdateData("sp_MAUpdateQty", new string[] {"@Items","@Qty" }, new object[] {Items,Qty });
                }
                LoadDataMA();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        //Cons
        #region[Update Cons]
        double? ActCons, EstCons, CusCons, BookCons;  
        private void bnt_OKCons_Click(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < gridView_Cons.RowCount; i++)
                {                    
                    OID = Convert.ToInt32(gridView_Cons.GetDataRow(i)["OID"]);
                    if (gridView_Cons.GetDataRow(i)["ActCons"].ToString() != "")
                        ActCons = Convert.ToDouble(gridView_Cons.GetDataRow(i)["ActCons"]);
                    if (gridView_Cons.GetDataRow(i)["EstCons"].ToString() != "")
                        EstCons = Convert.ToDouble(gridView_Cons.GetDataRow(i)["EstCons"]);
                    if (gridView_Cons.GetDataRow(i)["CusCons"].ToString() != "")
                        CusCons = Convert.ToDouble(gridView_Cons.GetDataRow(i)["CusCons"]);
                    if (gridView_Cons.GetDataRow(i)["BookCons"].ToString() != "")
                        BookCons = Convert.ToDouble(gridView_Cons.GetDataRow(i)["BookCons"]);
                    cls.UpdateData("sp_MAUpdateCons", new string[] { "@Items", "@OID", "@ActCons", "@EstCons", "@CusCons", "@BookCons", }, new object[] { Items, OID, ActCons, EstCons, CusCons, BookCons });                    
                }
                LoadDataMA();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[show Radial Menu]
        private void gridControl_Material_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {               
                 radialMenu_TrimList.ShowPopup(Control.MousePosition,true);
            }
        }
        #endregion

        #region[Export To Ecel]
        public void ExportToEcel(GridView GV)
        {
            String fileName = null;
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel 2003|*.xls|Excel 2007|*.xlsx";
            sfd.Title = "Save an Excel File";
            sfd.FileName = "TrimList_"+txt_MalNo.Text+"_"+ String.Format("{0:MMMddyyyy}", DateTime.Now);
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    fileName = sfd.FileName;
                    System.IO.FileStream fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.ReadWrite);
                    DevExpress.XtraPrinting.XlsExportOptions xlsOption = new DevExpress.XtraPrinting.XlsExportOptions();
                    xlsOption.TextExportMode = DevExpress.XtraPrinting.TextExportMode.Value;
                    xlsOption.ShowGridLines = false;
                    xlsOption.ExportMode = DevExpress.XtraPrinting.XlsExportMode.SingleFile;
                    xlsOption.TextExportMode = TextExportMode.Text;
                    xlsOption.SheetName = txt_MalNo.Text; 
                    GV.ExportToXls(fs, xlsOption);

                    fs.Close();
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("because it is being used by another process."))
                    {
                        MessageBox.Show("You can not save this file with the same name as another file. Choose a different name, or close other file before saving.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }

                Microsoft.Office.Interop.Excel.Application exApp = new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel.Workbook exBook = exApp.Workbooks.Open(fileName,
                0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);
                Microsoft.Office.Interop.Excel.Worksheet exSheet = (Microsoft.Office.Interop.Excel.Worksheet)exBook.Worksheets[1];
                try
                {
                    exSheet.Application.Columns.AutoFit();
                    exSheet.Application.Rows.AutoFit();
                    
                    // exSheet.Shapes.AddPicture(@"D:\Projects\COMO\Image\logo.png", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue,50, 50, 200, 50);
                    exSheet.Cells[1, 9] = "TRIM LIST DETAILS";                    
                    exSheet.Cells[2, 9] = DateTime.Now.ToShortDateString();                   
                    // Save file
                    exBook.Save();
                    exBook.Close(false, false, false);
                    exApp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(exBook);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(exApp);
                    DialogResult dlr = MessageBox.Show("Open File Export", "Do you want to open it?",
                                       MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dlr == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(fileName);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    exBook.Close(false, false, false);
                    exApp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(exBook);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(exApp);
                }
            }
            else
            {
                return;
            }
        }
        #endregion
        //------------------------------------
        #region [Preview]
        public void Preview()
        {
            GridView GV = bandedGridView_Material as GridView;
            FrmPreview prv = new FrmPreview(GV, ListItems);
            prv.LoadData();
            prv.Show();
        }
        #endregion

        #region [RadialMenu]
        private void RadialMenu_ItemClick(object sender, ItemClickEventArgs e)
        {
            radialMenu_TrimList.Collapse(false);
            GridView view = bandedGridView_Material as GridView;
            switch (e.Item.Caption)
            {
                case "Import":
                    radialMenu_TrimList.Collapse(false);
                    FrmImportTrimList ImPortTrim = new FrmImportTrimList(this,MALID);
                    ImPortTrim.ShowDialog();  
                    break;
                case "Export Excel":
                    try
                    {
                        radialMenu_TrimList.Collapse(false);                        
                        ExportToEcel(view);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    break;
                case "Refresh":
                    this.RunBackroundWorker();
                    break;
                case "Preview": 
                    FrmPreview prv = new FrmPreview(view, ListItems);
                    prv.LoadData();
                    prv.Show();
                    break;
                case "Delete Item":                    
                    if (view.FocusedRowHandle >= 0)
                    {
                       if (MessageBox.Show("Are you sure delete this item?", "Delete Item!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                       {
                            string item = view.GetFocusedDataRow()["MALDID"].ToString();
                            int kq = cls.UpdateData("sp_MADeleteSize", new string[] { "@Items" }, new object[] { item });
                            if (kq != 0)
                            {
                                cls.UpdateData("sp_MATrimDelete", new string[] { "@Items" }, new object[] { item });
                            }
                            LoadDataMA();
                        }
                    }
                    break;
                case "New Item":
                    //if(view.IsNewItemRow(view.FocusedRowHandle)
                    //{                        
                    //}
                    break;
                case "Delete Color":
                    try
                    {
                        if (view.FocusedRowHandle > 0 && view.IsNewItemRow(view.FocusedRowHandle) == false)
                        {
                            if (MessageBox.Show("Are you sure delete?", "Deleting...?", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                            {
                                cls.GetData("sp_MADeleteColor", new string[] { "@Items", "@OID" }, new object[] { Items, OID });
                                LoadDataMA();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    break;
                default :
                    break;
            }
        }
        #endregion
        
    }
}
